﻿using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using ZhCun.WebCommon.AL;
using ZhCun.WebCommon.ApiModels;
using ZhCun.WebCommon.DBModels;

namespace ZhCun.WebCommon.WebApi
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [CommonActionFilter]
    public class ApiController : ControllerBase
    {   
        string _RemoteIp;
        /// <summary>
        /// 返回远程请求地址
        /// </summary>
        protected string RemoteIp
        {
            get
            {
                if (_RemoteIp == null)
                {
                    _RemoteIp = Request.HttpContext.GetRemoteIp();
                }
                return _RemoteIp;
            }
        }
        /// <summary>
        /// 创建AL对象，并复制LoginHost
        /// </summary>
        protected virtual TAL CreateALObject<TAL>()
            where TAL : BaseAL, new()
        {
            TAL al  = new TAL();
            al.SetLoginHost(RemoteIp);
            return al;
        }
        /// <summary>
        /// 获取远程Ip地址
        /// </summary>
        [NonAction]
        protected string GetRemoteIp()
        {            
            return Request.HttpContext.GetRemoteIp();
        }
        /// <summary>
        /// 创建执行结果
        /// </summary>
        /// <param name="success">true：code=1，false：code=2</param>
        /// <param name="message">成功或错误消息</param>
        [NonAction]
        protected ApiResult CreateResult(bool success, string message)
        {
            return ApiResultFactory.CreateResult(success, message);
        }
        /// <summary>
        /// 创建一个执行成功的结果
        /// </summary>
        [NonAction]
        protected ApiResult CreateResult()
        {
            return CreateResult(true, "操作成功");
        }
        /// <summary>
        /// 创建一个成功并返回实体对象的结果
        /// </summary>
        [NonAction]
        protected ApiResult<T> CreateResult<T>(T data)
        {
            return ApiResultFactory.CreateResult<T>(data);
        }
        /// <summary>
        /// 创建一个成功并返回集合对象的结果
        /// </summary>
        [NonAction]
        protected ApiResultArray<T> CreateArrayResult<T>(IEnumerable<T> data,int count = 0)
        {
            return ApiResultFactory.CreateArrayResult<T>(data, count);
        }
    }

    /// <summary>
    /// webapi 不要登录验证的控制器基类(泛型指定AL对象)
    /// </summary>    
    public class ApiController<TAL> : ApiController
        where TAL : BaseAL, new()
    {
        TAL _AL;
        /// <summary>
        /// 当前控制器所依赖的AL对象
        /// </summary>
        public TAL ALObj
        {
            get
            {
                if (_AL == null)
                {
                    _AL = CreateALObject<TAL>();                    
                }
                return _AL;
            }
        }
    }
}